<?php

namespace app\admin\controller\cmstostatic;

use app\admin\model\cms\Channel as ChannelModel;
use app\common\controller\Backend;
use fast\Tree;


/**
 * 系统配置
 *
 * @icon fa fa-gears
 */
class Manage extends Backend
{
    /**
     * Channel模型对象
     */
    protected $model = null;
    protected $noNeedRight = ['get_fields_html', 'check_element_available'];
    /**
     * @var Tree
     */
    protected $tree = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\cms\Channel;

        $this->tree = Tree::instance();
        $this->tree->init(collection($this->model->order('weigh asc,id asc')->select())->toArray(), 'parent_id');
        $this->channelList = $this->tree->getTreeList($this->tree->getTreeArray(0), 'name');
        $this->modelList = \app\admin\model\cms\Modelx::order('id asc')->select();

        $this->view->assign("modelList", $this->modelList);
        $this->view->assign("channelList", $this->channelList);
        $this->view->assign("typeList", ChannelModel::getTypeList());
        $this->view->assign("statusList", ChannelModel::getStatusList());
        $this->view->assign("listtypeList", ChannelModel::getListtypeList());
        $this->view->assign("vipList", get_addon_info('vip') ? Service::getVipList() : []);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $search = $this->request->request("search");
            $model_id = $this->request->request("model_id");
            //构造父类select列表选项数据
            $list = [];
            if ($search) {
                foreach ($this->channelList as $k => $v) {
                    if (stripos($v['name'], $search) !== false || stripos($v['nickname'], $search) !== false) {
                        $list[] = $v;
                    }
                }
            } else {
                $list = $this->channelList;
            }
            foreach ($list as $index => $item) {
                if ($model_id && $model_id != $item['model_id']) {
                    unset($list[$index]);
                }
            }
            $list = array_values($list);
            $modelNameArr = [];
            foreach ($this->modelList as $k => $v) {
                $modelNameArr[$v['id']] = $v['name'];
            }
            foreach ($list as $k => &$v) {
                $v['pid'] = $v['parent_id'];
                $v['model_name'] = $v['model_id'] && isset($modelNameArr[$v['model_id']]) ? $modelNameArr[$v['model_id']] : __('None');
            }
            $total = count($list);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }


    public function synchronization()
    {
        $cmstostaticModel = new \app\admin\model\Cmstostatic;
        $cmstostaticMax = $cmstostaticModel->max('id');
        $cmschannelMax = $this->model->max('id');

        // 数据添加
        if($cmstostaticMax < $cmschannelMax){
            $cmstostaticDefault = [
                'isstatic' => '1',
                'dirname' => 'useless',
                'filename' => 'index.html',
                'indextype' => '0',
                'listtype' => 'list_{channel_id}_{page}.html',
                'showtype' => '{article_id}.html',
            ];

            for($i = $cmstostaticMax; $i < $cmschannelMax; $i++){
                $cmstostaticModel->data($cmstostaticDefault, true)->isUpdate(false)->save();
            }
        }

        // 数据更新
        $cmschannelSet = collection($this->model->order('id asc')->select())->toArray();
        $cmschannelRelation = [];
        foreach($cmschannelSet as $item){
            $cmschannelRelation[$item['id']] = $item;
        }

        $cmstostaticSet = collection($cmstostaticModel->order('id asc')->select())->toArray();
        $cmstostaticRelation = [];
        foreach($cmstostaticSet as $item){
            $cmstostaticRelation[$item['id']] = $item;
        }

        foreach($cmschannelSet as $cmschannel){
            // 新增更新
            $cmstostaticModel->where(['id'=>$cmschannel['id'], 'dirname'=>'useless'])->update(['dirname'=>$cmschannel['diyname']]);

            // 修改更新
            if(isset($cmstostaticRelation[$cmschannel['id']]) && $cmschannel['diyname'] != $cmstostaticRelation[$cmschannel['id']]['dirname']){
                $cmstostaticModel->where(['id'=>$cmschannel['id']])->update(['dirname'=>$cmschannel['diyname']]);
            }
        }

        // 数据删除 TODO 多余栏目数据可以不用删除，冗余在系统中不影响功能
        $cmstostaticModel->where(['dirname'=>'useless'])->delete();

        foreach($cmstostaticRelation as $cmstostatic){
            if(!isset($cmschannelRelation[$cmstostatic['id']])){
                $cmstostaticModel->where(['id'=>$cmstostatic['id']])->delete();
            }
        }

        $this->success(['total'=>$cmstostaticModel->count('id')]);
    }
}
